const jwt = require('jsonwebtoken')
const fs = require('fs')


const { PRIVATE_KEY } = require('../app/config')
const { UNAUTHORIZATION } = require('../constants/errot-type')
const errorType = require('../constants/errot-type')

class AuthController {
    async login(ctx, next) {

        console.log('ctx.user',ctx.user)
        const { id, username } = ctx.user
        let token = ''
        try {
                token = jwt.sign({id, username}, PRIVATE_KEY, {
                expiresIn: 60 * 60 * 24,
                algorithm: 'RS256'
            })
        } catch (error) {
            const err = new Error(errorType.TOKEN_GEN_MISTAKE)
            ctx.app.emit('error', err)
         }
         
        //  处理图片
        const imageBlob = ctx.user.avatar
        const imageBuffer = Buffer.from(imageBlob)
        const imageBase64 = imageBuffer.toString('base64')

        ctx.user.avatar = imageBase64
        ctx.body = {
            token,
            avatar: imageBase64,
            userInfo: ctx.user
        }
    }

    async sucess(ctx, next) {
        ctx.body = '授权成功 '
    }
}

module.exports = new AuthController()

